package cn.imvc.app.models;

import java.util.Date;
import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import cn.imvc.app.entities.Favorites;
import cn.imvc.app.entities.Voucher;
import cn.imvc.app.repositories.VoucherRepository;
import cn.imvc.data.domain.ViewRequest;

@Service
public class VoucherModelImpl implements VoucherModel {

	@Autowired
	private VoucherRepository voucherRepository;

	public Voucher get(int id) {
		return voucherRepository.findOne(id);
	}

	public Page<Voucher> find(ViewRequest viewRequest) {
		return (Page<Voucher>) voucherRepository.findAll();
	}

	public Voucher save(Voucher voucher) {

		Voucher voucher2 = voucherRepository.saveAndFlush(voucher);

		return voucher2;
	}

	public Voucher update(Voucher newVoucher) {
		Voucher loadVoucher = get(newVoucher.getId());
		BeanUtils.copyProperties(newVoucher, loadVoucher, new String[] { "id" });

		return voucherRepository.saveAndFlush(loadVoucher);
	}

	public void delete(int id) {
		voucherRepository.delete(id);

	}

	public void deleteBatch(int[] ids) {

		for (int id : ids) {
			delete(id);
		}

	}

	public Voucher checkIsValid(int orderAmount, Integer voucherId) {
		Voucher voucher = voucherRepository.getOne(voucherId);
		if (voucher != null) {
			Integer limitMoney = voucher.getLimitMoney();
			Byte state = voucher.getState();
			long now = System.currentTimeMillis();
			long startTime = voucher.getStartDate().getTime();
			long endTime = voucher.getEndDate().getTime();
			if(state==0&&limitMoney<=orderAmount&&(now>=startTime&&now<=endTime)){
				return voucher;
			}
		}
		return null;
	}

	public List<Voucher> getVouchersInfoByOrderAmount(Integer memberId, int orderAmount,byte state,Date nowDate) {
		return voucherRepository.findByMemberIdAndLimitMoneyLessThanAndStateAndStartDateLessThanAndEndDateGreaterThan(memberId, orderAmount, state, nowDate, nowDate);
	}
	
	public Page<Voucher> findByMemberId(Integer memberId, PageRequest pageRequest) {
		return (Page<Voucher>) voucherRepository.findByMemberId(memberId, pageRequest);
	}

}
